

require('./client/eui');


// 设置app workDir
let app = window.electron.remote.app;
let workDir = window.workDir = app.getAppPath();
console.log('workDir:',workDir);

// cocos打包后目录
let cocosDir = window.path.join(workDir,'../build/web-desktop');

function async_loadAllJs(lstJs){
    let lstPromise = lstJs.map(js=>{
        return async_loadScript(js);
    });
    return Promise.all(lstPromise);
}

function sortLoadJsFile(lstJs){
    let getCocos2dJsIdx = function () {
        for(let i = 0; i < lstJs.length; ++i){
            let jsFile = lstJs[i];
            let idx = jsFile.indexOf('cocos2d-js');
            if(idx >= 0){
                return i;
            }
        }
        return -1;
    };

    let idx = getCocos2dJsIdx();
    if(idx > 0){
        console.log('交换cocos2d-js 位置');
        // idx 和 0 交换
        let tmp = lstJs[idx];
        lstJs[idx] = lstJs[0];
        lstJs[0] = tmp;
    }
}

window.onload = function () {

    let lstJs = [];

    let path = window.path;
    let fs = window.fs;

    // 先加载settings
    let srcDir = path.join(cocosDir,'src');
    let srcFils = fs.readdirSync(srcDir);
    srcFils.forEach(file=>{
        let extname = path.extname(file);
        if (extname === '.js') {
            // 过滤掉 project.dev.7ad19.js
            // 会在 main.js 中去加载
            if(!file.startsWith('project.dev')){
                lstJs.push(`src/${file}`);
            }
        }
    });

    let files = fs.readdirSync(cocosDir);
    files.forEach(file => {
        let extname = path.extname(file);
        if (extname === '.js') {
            lstJs.push(file);
        }
    });

    // 让  cocos2d-js  先加载
    sortLoadJsFile(lstJs);
    console.log('lstJs:',lstJs);

    async_loadAllJs(lstJs).then(()=>{
        console.log('==所有脚本加载成功=====!');
        // 开始启动引擎---------------
        console.log('===========start engine===============');
        window.boot();
    }).catch(()=>{
         console.log('==============加载脚本失败!================');
    });
};


function async_loadScript(moduleName) {
    return new Promise(function (resolve, reject) {

        function scriptLoaded() {
            document.body.removeChild(domScript);
            domScript.removeEventListener('load', scriptLoaded, false);
            resolve();
        }

        let domScript = document.createElement('script');
        domScript.async = true;
        domScript.src = moduleName;
        domScript.addEventListener('load', scriptLoaded, false);
        domScript.addEventListener('error',()=>{
            reject();
        },false);
        document.body.appendChild(domScript);
    });
}
